﻿// 遍历当前进程和线程.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//

#include "pch.h"
#include <iostream>
#include <stdio.h>
#include <Windows.h>
#include <TlHelp32.h>
#include <Psapi.h>

#include <tlhelp32.h>
#pragma comment(lib,"kernel32.lib")

#pragma comment(lib,"user32.lib")
#pragma comment(lib,"advapi32.lib")




/*
遍历所有进程的两套函数：
    CreateToolhelp32Snapshot                获取当前时间点  的进程映射

    Process32First  Process32Next


*/

//打印
void printCurrentProcessInfo();


//遍历所有进程并打印id和名字：
void travelProcess();


//遍历指定进程中的所有线程并打印id(线程没有名字）：
void travelAllThread(DWORD processId);

int main()
{
    
    printCurrentProcessInfo();


    //遍历所有进程：
    //travelProcess();


    travelAllThread(GetCurrentProcessId());



    return 0;
}

void printCurrentProcessInfo()
{
    //获取当前进程id：
    DWORD currentProcessId = GetCurrentProcessId();

    //获取当前文件名：
    char exeName[MAX_PATH] = { 0 };
    GetModuleFileNameExA(GetCurrentProcess(), NULL,exeName,MAX_PATH);

    printf("currentProcessId:%d\n", currentProcessId);
    printf("currentProcessName:%s\n", exeName);
}
void travelProcess()
{
    //
    HANDLE processSnapshot =  CreateToolhelp32Snapshot(TH32CS_SNAPALL, GetCurrentProcessId());        //快照
    if (INVALID_HANDLE_VALUE == processSnapshot)
    {
        printf("获取快照失败:%d\n",GetLastError());
        return;
    }
    printf("获取快照成功\n");



    PROCESSENTRY32 processEntry = { 0 };
    processEntry.dwSize = sizeof(processEntry);

    BOOL isDone =  Process32First(processSnapshot, &processEntry/*结构体  entry的信息*/);
    if (0 == isDone)
        printf("error:%d\n", GetLastError());



    while (isDone)
    {
        printf("processId:%d\tprocessName:%s\n",
            processEntry.th32ProcessID,
            processEntry.szExeFile);

        isDone = Process32Next(processSnapshot, &processEntry);     //肯定是false

    }

    CloseHandle(processSnapshot);       //记得要关闭

}

void travelAllThread(DWORD processId)
{
    printf("------------id---------\n");
    HANDLE threadSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, NULL);


    THREADENTRY32 threadEntry = { 0 };
    threadEntry.dwSize = sizeof(threadEntry);

    BOOL isDone = Thread32First(threadSnapshot, &threadEntry);
    if (0 == isDone)
    {
        printf("error: %d\n", GetLastError());

    }
    while (isDone)
    {
        printf("threadId: %d\n", threadEntry.th32ThreadID);

        isDone = Thread32Next(threadSnapshot, &threadEntry);
    }
}